//
//  GamecommentViewController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/11/24.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "GamecommentViewController.h"
#import "CommentModel.h"
#import "CommentViewCell.h"
#import "MJRefresh.h"
#import "EvaluationDetailViewController.h"

@interface GamecommentViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIButton *_listfootbtn;
    NSInteger next_key;
    
    BOOL _isError;
    
    UILabel *_msgLb;
}

@end

@implementation GamecommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startCollect) name:@"startcollect" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endCollect) name:@"endcollect" object:nil];
    
    _listArr = [NSMutableArray array];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 30)];
    label.text = @"游戏测评";
    self.navigationItem.titleView = label;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    self.width = WIDTH -20;
    self.bannerView.x = 10;
    self.bannerView.y = 5;
    self.bannerView2.x = 10;
    self.bannerView2.y = 5;
    [self createTable];
    [self creatHeader];
    
    [self createData];
    
}
- (void)startCollect
{
    NSLog(@"----------------start");
    [self workBlock:self.scrollView with:self.adArr];
}

- (void)endCollect
{
    NSLog(@"----------------end");
    
    [self restBlock:self.scrollView];
}
- (void)addModelUPnum:(NSNotification *)noti
{
    CommentModel *model = [noti object];
    for (CommentModel *mo in _listArr) {
        if ([mo.commentid isEqualToString:model.commentid]) {
            mo.is_up = [NSString stringWithFormat:@"%ld",   mo.is_up.integerValue + 1];
            mo.up_num = [NSString stringWithFormat:@"%ld",mo.up_num.integerValue + 1];
            [_tableView reloadData];
        }
    }
}
-(void)creatHeader
{
    [[MyAd sharedMyad]headerViewwithTag:@"evaluation_game" target:self back:^(UIView *headView,NSArray *dataArr,bool iserror) {
        if (headView) {
            
            self.scrollView = (SDCycleScrollView *)headView;
            self.adArr = dataArr;
            _isError = iserror;
            self.tableView.tableHeaderView = headView;
            [self workBlock:self.scrollView with:self.adArr];
            self.scrollView.shouldGetoffset = YES;
        }
        
    }];
}
- (NSString *)url
{
    NSString *str = [ISBUS boolValue]?[NSString stringWithFormat:@"%@/port/newsGame",CAR_URL]:GAMECOMMENT;
    
    return str;
}

- (void)createData
{
    if (next_key == NSNotFound) {
        Message(@"亲,到底了");
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        return;
    }
    
    NSDictionary *parameter;
    if (!USERID) {
        parameter = @{@"next_key":@(next_key),@"page_size":@(10)};
    }else{
        parameter = @{@"next_key":@(next_key),@"page_size":@(10),@"user_id":USERID};
    }
    
    NSString *str = [self url];
    [self.view Loading_0000];
    [MyAFN POST:str parameters:parameter block:^(id responseObject) {
        [self.view Hidden];
        NSDictionary *gamelistDic = responseObject;
        if ([[gamelistDic objectForKey:@"status"]integerValue]) {
            if ([[gamelistDic objectForKey:@"next_key"]integerValue]) {
                next_key = [[gamelistDic objectForKey:@"next_key"] integerValue];
                
                
            }else{
                next_key = NSNotFound;
            }
            [[EGOCache globalCache]setObject:gamelistDic forKey:@"gamecomment"];
            [self getContent:gamelistDic];
        }
        
        if (!_listArr.count) {
            [self showMessage];
        }else{
            [self hideMessage];
        }
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }error:^(NSError *error) {
        [self.view Hidden];
        if ([[EGOCache globalCache]objectForKey:@"gamecomment"]) {
            
            [self getContent:(NSDictionary *)[[EGOCache globalCache]objectForKey:@"gamecomment"]];
        }
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }fromController:nil];
}

- (void)getContent:(NSDictionary *)response
{
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *modelDic in [response objectForKey:@"evaluationList"]) {
        CommentModel *model = [[CommentModel alloc]init];
        [model setValuesForKeysWithDictionary:modelDic];
        [arr addObject:model];
    }
    if (arr.count) {
        [_listArr addObjectsFromArray:arr];
        if (arr.count >=5) {
            [_listArr addObject:@"ad"];
        }
        
        [self.tableView reloadData];
    }
}

- (void)showMessage
{
    if (!_msgLb) {
        _msgLb = [[UILabel alloc]init];
    }
    
    if (!self.tableView.tableHeaderView) {
        _msgLb.frame = CGRectMake(20, 20, WIDTH - 40, 50);
    }else{
        _msgLb.frame = CGRectMake(20, SCALEY*(179)+90+20, WIDTH - 40, 50);
    }
    _msgLb.text = @"暂时没有资源";
    _msgLb.textAlignment = NSTextAlignmentCenter;
    _msgLb.textColor = [UIColor lightGrayColor];
    _msgLb.font = [UIFont systemFontOfSize:18];
    [_tableView addSubview:_msgLb];
}
- (void)hideMessage
{
    [_msgLb removeFromSuperview];
}
- (void)createTable
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 49 - 64) style:UITableViewStylePlain];
   // self.tableView.showsVerticalScrollIndicator = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CommentViewCell" bundle:nil] forCellReuseIdentifier:@"CommentViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GameCommentAdCell" bundle:nil] forCellReuseIdentifier:@"GameCommentAdCell"];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(createData)];
    [self.tableView delsetExtraline];
    self.tableView.header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    
}

- (void)refresh
{
    next_key = 0;
    [_listArr removeAllObjects];
    [_tableView reloadData];
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _listArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[_listArr objectAtIndex:indexPath.row]isKindOfClass:[NSString class]]) {
        
        return GDTMOB_AD_SUGGEST_SIZE_320x50.height+10;
    }else{
        return 80*SCALEX;
    }
    return 80*SCALEX;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([[_listArr objectAtIndex:indexPath.row]isKindOfClass:[NSString class]]) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aaa"];
        }
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        if ((indexPath.row+1)%22) {
            [cell.contentView addSubview:self.bannerView2];
        }else{
            [cell.contentView addSubview:self.bannerView];
        }
        
        return cell;

        
    }else{
        CommentViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentViewCell"];
        
        CommentModel *model = [_listArr objectAtIndex:indexPath.row];
        [cell showModel:model];
        
        cell.updown = ^{
            
            if (!USERID) {
                [self.view Message:@"请登录" HiddenAfterDelay:1];
                return;
            }
            
            NSDateFormatter *formater = [[NSDateFormatter alloc]init];
            [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *date = [formater stringFromDate:[NSDate date]];
            
            NSDictionary *parameters = @{@"obj_id":model.commentid,@"is_up_down":@(0),@"user_id":USERID,@"date":date};
            
            
            [MyAFN POST:UpDown parameters:parameters block:^(id responseObject) {
                
                NSDictionary *response = responseObject;
                
                if ([[response objectForKey:@"status"]integerValue]==1) {
                    [self.view Message:@"点赞成功" HiddenAfterDelay:1];
                    
                    model.up_num = [NSString stringWithFormat:@"%ld",cell.upLb.text.integerValue + 1];
                    model.is_up = [NSString stringWithFormat:@"%ld",model.is_up.integerValue+1];
                    
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO];
                    
                }else if ([[response objectForKey:@"status"]isEqualToString:@"005"]){
                    
                    NSLog(@"00000000000555555");
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userid"];
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userpwd"];
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"username"];
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"usericon"];
                    
                }else{
                    NSLog(@"%@",[response objectForKey:@"msg"]);
                }
                
            }error:^(NSError *error) {
                
            }fromController:nil];
        };
        
        return cell;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = [_listArr objectAtIndex:indexPath.row];
    
    if ([obj isKindOfClass:[NSString class]]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    CommentModel *model = [_listArr objectAtIndex:indexPath.row];
    //self.passCommentModel(model);
    EvaluationDetailViewController *controller = [[EvaluationDetailViewController alloc]init];
    __weak GamecommentViewController *weakComment = self;
    controller.model = model;
    //更新点赞数
    controller.updateModel = ^{
        
        [weakComment.tableView reloadData];
    };
    [self.navigationController pushViewController:controller animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void)workBlock:(SDCycleScrollView *)view with:(NSArray *)arr
{
    [self restBlock:self.scrollView];
    if (self.tabBarController.selectedIndex != 1) {
        
        return;
    }
    if (!arr.count||!view) {
        
        return;
    }
    NSLog(@"开始统计");
    __weak NSArray *slide = arr;
    view.getContentOffset = ^(float offset){
        
        if (!_isError) {
            int i;
            
            if (offset == 0) {
                
                i = 0;
            }else{
                int index = offset/WIDTH;
                i = index%arr.count ;
            }
            
            NSLog(@"++++%d",i);
            if (i<slide.count) {
                BannerModel *model = slide[i];
                [MyAd collectShowAd:model];
            }
            
        }
    };
}

- (void)restBlock:(SDCycleScrollView *)view
{
    NSLog(@"不统计了》》》》》》》");
    if (view) {
        view.getContentOffset = ^(float offset){
            
            
        };
    }
    
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (!self.adArr.count) {
        return;
    }
    BannerModel *model = [self.adArr objectAtIndex:index];
    
    [MyAd collectClickAd:model];
    
    AdViewController *controller = [[AdViewController alloc]init];
    controller.urlstr = model.href;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self restBlock:self.scrollView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.scrollView) {
        
        [self workBlock:self.scrollView with:self.adArr];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
